package com.example.choupaiapp.main.activity.publish;

import android.content.Context;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.TranslateAnimation;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.adapter.BaseAdapterHelper;
import com.example.choupaiapp.common.adapter.QuickAdapter;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.activity.home.SearchLocationActivity;
import com.example.choupaiapp.main.bean.PublishMapLocationBean;
import com.example.choupaiapp.main.util.LocationUtil;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2020/4/22.
 */

public class PublishMapViewActivity extends CommonActivity implements PoiSearch.OnPoiSearchListener, OnRefreshLoadMoreListener {

    @BindView(R.id.map)
    MapView mapView;
    @BindView(R.id.search_ll)
    LinearLayout search_ll;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.listview)
    ListView listView;
    @BindView(R.id.linear)
    LinearLayout linear;
    private AMap aMap;
    private UiSettings mUiSettings;
    Marker screenMarker = null;
    private CameraPosition mPostion = null;
    private LatLng latLng;
    private LatLng locationL;
    private int pageSize = 20;
    private int pageNum = 1;
    private QuickAdapter<PoiItem> quickAdapter;
    private LatLng la;
    private boolean isSure = true;
    private String citycode;
    private String city;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_mapview);

        EventBus.getDefault().register(this);
        mapView.onCreate(savedInstanceState); // 此方法必须重写

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            double lat = bundle.getDouble("lat");
            double lon = bundle.getDouble("lon");
            citycode = bundle.getString("citycode");
            city = bundle.getString("city");
            locationL = new LatLng(lat, lon);
            latLng = new LatLng(lat, lon);
        }

        if (aMap == null) {
            aMap = mapView.getMap();
            mUiSettings = aMap.getUiSettings();
            mUiSettings.setZoomControlsEnabled(false);
            mUiSettings.setTiltGesturesEnabled(false);
            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(latLng, 18, 30, 0)));
        }
        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                addMarkersToMap();
            }
        });

        // 设置可视范围变化时的回调的接口方法
        aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
            @Override
            public void onCameraChange(CameraPosition position) {
                mPostion = position;
                isSure = false;
            }

            @Override
            public void onCameraChangeFinish(CameraPosition postion) {
                //屏幕中心的Marker跳动
                isSure = true;
                pageNum = 1;
                LocationUtil.getInstance().searchPoiOption(city, citycode, PublishMapViewActivity.this, 10000, postion.target.latitude, postion.target.longitude);
                LocationUtil.getInstance().setQuery(pageNum++, pageSize);
                LocationUtil.getInstance().searchPoi();
                startJumpAnimation();
            }
        });


        quickAdapter = new QuickAdapter<PoiItem>(context, R.layout.item_publish_location) {
            @Override
            protected void convert(BaseAdapterHelper helper, PoiItem item) {
                helper.setText(R.id.location, item.getTitle());
                helper.setText(R.id.address, item.getSnippet());
            }
        };
        listView.setAdapter(quickAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                la = new LatLng(quickAdapter.getItem(i).getLatLonPoint().getLatitude(), quickAdapter.getItem(i).getLatLonPoint().getLongitude());
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(la, 18, 30, 0)));
            }
        });

        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        pageNum = 1;
        LocationUtil.getInstance().searchPoiOption(city, citycode, this, 10000, latLng.latitude, latLng.longitude);
        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
        LocationUtil.getInstance().searchPoi();
        refreshLayout.setEnableLoadMore(true);

    }

    public boolean isTop(final AbsListView listView) {
        boolean result = false;
        if (listView.getFirstVisiblePosition() == 0) {
            final View topChildView = listView.getChildAt(0);
            if (topChildView != null) {
                result = topChildView.getTop() == 0;
            }
        }
        return result;
    }

    private void addMarkersToMap() {
        Point screenPosition = aMap.getProjection().toScreenLocation(latLng);
        screenMarker = aMap.addMarker(new MarkerOptions()
                .position(latLng)
                .anchor(0.5f, 0.5f)
                .icon(BitmapDescriptorFactory.fromView(getLayoutInflater().inflate(R.layout.publish_map_marker_small, null))));

        screenMarker.setPositionByPixels(screenPosition.x, screenPosition.y);

    }

    /**
     * 屏幕中心marker 跳动
     */
    public void startJumpAnimation() {

        if (screenMarker != null) {
            //根据屏幕距离计算需要移动的目标点
            final LatLng latLng = screenMarker.getPosition();
            Point point = aMap.getProjection().toScreenLocation(latLng);
            point.y -= dip2px(this, 125);
            LatLng target = aMap.getProjection()
                    .fromScreenLocation(point);
            //使用TranslateAnimation,填写一个需要移动的目标点
            Animation animation = new TranslateAnimation(target);
            animation.setInterpolator(new Interpolator() {
                @Override
                public float getInterpolation(float input) {
                    // 模拟重加速度的interpolator
                    if (input <= 0.5) {
                        return (float) (0.5f - 2 * (0.5 - input) * (0.5 - input));
                    } else {
                        return (float) (0.5f - Math.sqrt((input - 0.5f) * (1.5f - input)));
                    }
                }
            });
            //整个移动所需要的时间
            animation.setDuration(600);
            //设置动画
            screenMarker.setAnimation(animation);
            //开始动画
            screenMarker.startAnimation();

        } else {
            Log.e("amap", "screenMarker is null");
        }
    }

    //dip和px转换
    private static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    /**
     * 方法必须重写
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.sure, R.id.location_iv, R.id.search_ll})
    public void onViewClicked(View view) {
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.sure:
                if (isSure) {
                    if (mPostion != null) {
//                    Logger.e(aMap.getCameraPosition().zoom+"");
                        EventBus.getDefault().post("location_mapView" + ":" + mPostion.target.latitude + ":" + mPostion.target.longitude);
                        finishActivity();
                    } else {
                        showImageToas("请稍等地图加载完毕");
                    }
                } else {
                    showImageToas("请稍等地图加载完毕");
                }

                break;
            case R.id.location_iv:
                aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(locationL, 18, 30, 0)));
                break;
            case R.id.search_ll:
                Bundle bundle = new Bundle();
                bundle.putString("flag", "publish_map");
                bundle.putString("citycode", citycode);
                startActivity(SearchLocationActivity.class, bundle);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void OnMessageEvent(PublishMapLocationBean event) {
        la = new LatLng(event.getPoiItem().getLatLonPoint().getLatitude(), event.getPoiItem().getLatLonPoint().getLongitude());
        aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(la, 18, 30, 0)));
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        if (i == 1000 && poiResult != null && poiResult.getPois().size() > 0) {
            if (pageNum == 2) {
                quickAdapter.clear();
            }
            quickAdapter.addAll(poiResult.getPois());
            quickAdapter.notifyDataSetChanged();
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();

            if (pageNum == 2) {
                listView.setSelection(0);
            }
        } else {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            showImageToas("附近暂无数据");
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
        LocationUtil.getInstance().searchPoi();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        LocationUtil.getInstance().setQuery(pageNum++, pageSize);
        LocationUtil.getInstance().searchPoi();
    }
}
